package com.plian.system.service.glcydgz.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.UserCache;
import com.plian.system.common.status.CheckStatus;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dto.pf.BaseBusinessAnnualDTO;
import com.plian.system.entity.fr.indicators.FinanceIndicators;
import com.plian.system.entity.fr.indicators.IndicatorsValue;
import com.plian.system.entity.pf.*;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.mapper.fr.indicators.FinanceIndicatorsMapper;
import com.plian.system.mapper.fr.indicators.IndicatorsValueMapper;
import com.plian.system.mapper.pf.BaseBusinessAnnualMapper;
import com.plian.system.mapper.pf.BaseBusinessAuditMapper;
import com.plian.system.mapper.pf.TaskIndicatorsMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.glc.IGlcBaseBusinessIndicatorsService;
import com.plian.system.service.glcydgz.IGlcBaseBusinessAnnualService;
import com.plian.system.service.glcydgz.IGlcBaseBusinessProgressService;
import com.plian.system.service.pf.*;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.*;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.pf.BaseBusinessAnnualWrapper;
import com.plian.system.wrapper.pf.BusinessAnnualWrapper;
import com.plian.system.wrapper.pf.MainAnnualWrapper;
import com.plian.system.wrapper.pf.TaskAnnualWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.GZW_TYPE;
import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * @Author: Take-off
 * @Description: TODO 经营业绩考核年度主表 服务实现类
 * @Date: 2022/12/18 2:46 PM
 * @Version: 1.0
 **/
@Slf4j
@Service
@AllArgsConstructor
public class GlcBaseBusinessAnnualServiceImpl extends BaseServiceImpl<BaseBusinessAnnualMapper, BaseBusinessAnnual> implements IGlcBaseBusinessAnnualService, BaseFlowService {

    private FormWorkflowService formWorkflowService;

    private IFormCodeService formCodeService;

    private IBusinessAnnualService businessAnnualService;

    private BusinessAnnualWrapper businessAnnualWrapper;

    private BaseBusinessAnnualWrapper baseBusinessAnnualWrapper;

    private IGlcBaseBusinessIndicatorsService glcBaseBusinessIndicatorsService;

    private IGlcBaseBusinessProgressService glcBaseBusinessProgressService;

    private IMainAnnualService mainAnnualService;

    private MainAnnualWrapper mainAnnualWrapper;

    private ISelfAssessmentService selfAssessmentService;

    private ITaskAnnualService taskAnnualService;

    private TaskAnnualWrapper taskAnnualWrapper;

    private BaseBusinessAuditMapper baseBusinessAuditMapper;

    private IBusinessAuditService businessAuditService;

    private ITaskAuditService taskAuditService;

    private IMainAuditService mainAuditService;

    private IAppraisalIndexService appraisalIndexService;

    private FinanceIndicatorsMapper indicatorsMapper;

    private IndicatorsValueMapper indicatorsValueMapper;

    private IAuditAssetsService auditAssetsService;

    private IOrgService orgService;

    private IApprovalMessageService approvalMessageService;

    private TaskIndicatorsMapper taskIndicatorsMapper;
    @Override
    public boolean saveOrUpdate(BaseBusinessAnnual baseBusinessAnnual) {
        baseBusinessAnnual.setModuleType(1);
        if (!Optional.ofNullable(baseBusinessAnnual.getStatus()).isPresent()) {
            baseBusinessAnnual.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (baseBusinessAnnual.getStatus().equals(FormStatusConstant.REJECT)) {
            baseBusinessAnnual.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (!Optional.ofNullable(baseBusinessAnnual.getId()).isPresent()) {
            baseBusinessAnnual.setCode(formCodeService.getCode(FormTypeConstant.GLC_BUSINESS_ANNUAL));
            baseBusinessAnnual.setFormType(String.valueOf(FormTypeConstant.GLC_BUSINESS_ANNUAL));
        }
        if (!Optional.ofNullable(baseBusinessAnnual.getIsAudit()).isPresent()) {
            baseBusinessAnnual.setIsAudit(0);
        }
        return super.saveOrUpdate(baseBusinessAnnual);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            BaseBusinessAnnual baseBusinessAnnual = getById(id);
            if (baseBusinessAnnual == null) {
                return false;
            } else if (baseBusinessAnnual.getStatus() != null &&
                    (baseBusinessAnnual.getStatus() != FormStatusConstant.STASH && baseBusinessAnnual.getStatus() != FormStatusConstant.UNREVIEWED)) {
                return false;
            }
            formWorkflowService.deleteProcessInstance(String.valueOf(id));
        }

        boolean result = super.deleteLogic(ids);
        if (result){
            businessAnnualService.deleteByParentId(ids);
            taskAnnualService.deleteByParentId(ids);
            mainAnnualService.deleteByParentId(ids);
            selfAssessmentService.deleteByParentId(ids);
        }
        return result;
    }

    @Override
    public HashMap<String,Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW,null);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
        BaseBusinessAnnual baseBusinessAnnual = getById(id);
        BaseBusinessAnnualVO baseBusinessAnnualVO = baseBusinessAnnualWrapper.entityToVO(baseBusinessAnnual);
        BaseBusinessAnnualVO pageData = getDetailObj(baseBusinessAnnualVO).getPageData();
        saveBaseBusinessAudit(pageData);
        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH,"审批通过");
    }

    @Override
    public Boolean reject(String id, int formState,String comment) {
        return handleStatus(Long.valueOf(id), formState,comment);
    }

    @Override
    public String checkYear(BaseBusinessAnnual baseBusinessAnnual) {
        String fillingYear = baseBusinessAnnual.getFillingYear();
        String fillingUnitId = baseBusinessAnnual.getFillingUnitId();
        QueryWrapper<BaseBusinessAnnual> queryWrapper = new QueryWrapper<>();
        if (!Optional.ofNullable(fillingYear).isPresent()) {
            return "填报时间为空";
        }
        if (!Optional.ofNullable(fillingUnitId).isPresent()){
            return "填报单位为空";
        }
        //判断该时间的基础表
        List<BaseBusinessIndicators> baseBusinessIndicators = glcBaseBusinessIndicatorsService.list(new LambdaQueryWrapper<BaseBusinessIndicators>().eq(BaseBusinessIndicators::getStatus, 3).eq(BaseBusinessIndicators::getIsLatest,2)
                .eq(BaseBusinessIndicators::getFillingYear, fillingYear).eq(BaseBusinessIndicators::getModuleType,2).eq(BaseBusinessIndicators::getFillingUnitId, fillingUnitId));
        if (CollectionUtil.isEmpty(baseBusinessIndicators)){
            return "该年度基础表没填";
        }
        //获取12月份数据
        List<BaseBusinessProgress> list = glcBaseBusinessProgressService.list(new LambdaQueryWrapper<BaseBusinessProgress>()
                .eq(BaseBusinessProgress::getFillingMonth, fillingYear + "-12").eq(BaseBusinessProgress::getModuleType,1).eq(BaseBusinessProgress::getFillingUnitId, fillingUnitId));
        if (CollectionUtil.isEmpty(list)){
            return "该年度12月份考核进度没填";
        }

        queryWrapper.eq("filling_unit_id", fillingUnitId);
        queryWrapper.eq("filling_year", fillingYear);
        queryWrapper.eq("module_type",1);
        BaseBusinessAnnual one = getOne(queryWrapper);
        if (!Optional.ofNullable(one).isPresent()){
            return null;
        }
        if (one.getId().equals(baseBusinessAnnual.getId())){
            return null;
        }
        return "该年度已填报";
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id          主键
     * @param updateStatus  更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus,String comment) {
        try {
            BaseBusinessAnnual baseBusinessAnnual = getById(id);
            /**
             * 设置审批人和审批时间
             */
            if (updateStatus == FormStatusConstant.FINISH){
                baseBusinessAnnual.setApprovedUser(TokenUtil.getTokenUserId());
                Date now = DateUtil.now();
                baseBusinessAnnual.setApprovedTime(now);
            }
            if (StringUtil.isNotBlank(baseBusinessAnnual.getDataSource()) &&
                    StringUtil.isNotBlank(baseBusinessAnnual.getDataSourceId())){
                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
                    ApprovalMessage approvalMessage = new ApprovalMessage();
                    approvalMessage.setDataSourceId(baseBusinessAnnual.getDataSourceId());
                    approvalMessage.setOpinion(comment);
                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
                    approvalMessage.setIsSend(1);
                    approvalMessage.setDataSourceType(GZW_TYPE);

                    if (baseBusinessAnnual.getDataSource().equals(YthConstant.DATA_NINGBO)) {
                        approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                        approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                        approvalMessage.setFormType(FormTypeConstant.GLC_BUSINESS_ANNUAL);
                        approvalMessage.setFilingCode(baseBusinessAnnual.getCode());
                    }
                    approvalMessageService.save(approvalMessage);
                }
            }
            baseBusinessAnnual.setStatus(updateStatus);
            updateById(baseBusinessAnnual);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<BaseBusinessAnnual> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(BaseBusinessAnnual::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        queryWrapper.eq(BaseBusinessAnnual::getModuleType,1);
        List<BaseBusinessAnnual> baseBusinessAnnuals = list(queryWrapper);
        List<BaseBusinessAnnualVO> baseBusinessAnnualVOS = baseBusinessAnnualWrapper.entityToVO(baseBusinessAnnuals);
        List<PageData> pageDataList = new ArrayList<>();
        try{
            if (CollectionUtil.isNotEmpty(baseBusinessAnnualVOS)){
                for (BaseBusinessAnnualVO vo : baseBusinessAnnualVOS){
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getFillingUnitName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getFillingUnitId());
                    pd.put("formType", FormTypeConstant.GLC_BUSINESS_ANNUAL);
                    pd.put("orgName", vo.getFillingUnitName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.GLC_BUSINESS_ANNUAL);
    }


    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED, null);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean submit(BaseBusinessAnnual baseBusinessAnnual) {
        baseBusinessAnnual.setModuleType(1);
        boolean result = saveOrUpdate(baseBusinessAnnual);
        if (result){
            List<BusinessAnnual> baseIndicators = baseBusinessAnnual.getBaseIndicators();
            List<BusinessAnnual> categoryIndicators = baseBusinessAnnual.getCategoryIndicators();
            List<BusinessAnnual> industryIndicators = baseBusinessAnnual.getIndustryIndicators();
            List<BusinessAnnual> otherIndicators = baseBusinessAnnual.getOtherIndicators();
            if (CollectionUtil.isNotEmpty(baseIndicators)){
                if(CollectionUtil.isNotEmpty(categoryIndicators)) baseIndicators.addAll(categoryIndicators);
                if(CollectionUtil.isNotEmpty(industryIndicators)) baseIndicators.addAll(industryIndicators);
                if(CollectionUtil.isNotEmpty(otherIndicators)) baseIndicators.addAll(otherIndicators);
                for (BusinessAnnual businessAnnual : baseIndicators){
                    if (businessAnnual.getId() != null &&
                            Optional.ofNullable(businessAnnual.getIsDeleted()).isPresent() && businessAnnual.getIsDeleted().intValue() == 1) {
                        businessAnnualService.removeById(businessAnnual.getId());
                    } else {
                        businessAnnual.setBaseBusinessAnnualId(baseBusinessAnnual.getId());
                        businessAnnualService.saveOrUpdate(businessAnnual);
                    }
                }
            }

//            List<BusinessAnnual> businessAnnuals = baseBusinessAnnual.getBusinessAnnuals();
//            if (CollectionUtil.isNotEmpty(businessAnnuals)){
//                for (BusinessAnnual businessAnnual : businessAnnuals){
//                    if (businessAnnual.getId() != null &&
//                            Optional.ofNullable(businessAnnual.getIsDeleted()).isPresent() && businessAnnual.getIsDeleted().intValue() == 1) {
//                        businessAnnualService.removeById(businessAnnual.getId());
//                    }else {
//                        businessAnnual.setBaseBusinessAnnualId(baseBusinessAnnual.getId());
//                        businessAnnualService.saveOrUpdate(businessAnnual);
//                    }
//                }
//            }
//
//            List<TaskAnnual> taskAnnuals = baseBusinessAnnual.getTaskAnnuals();
//            if (CollectionUtil.isNotEmpty(taskAnnuals)){
//                for (TaskAnnual taskAnnual : taskAnnuals){
//                    if (taskAnnual.getId() != null &&
//                            Optional.ofNullable(taskAnnual.getIsDeleted()).isPresent() && taskAnnual.getIsDeleted().intValue() == 1) {
//                        taskAnnualService.removeById(taskAnnual.getId());
//                    }else {
//                        taskAnnual.setBaseBusinessAnnualId(baseBusinessAnnual.getId());
//                        taskAnnualService.saveOrUpdate(taskAnnual);
//                    }
//                }
//            }

            List<MainAnnual> mainAnnuals = baseBusinessAnnual.getMainAnnuals();
            if (CollectionUtil.isNotEmpty(mainAnnuals)){
                for (MainAnnual mainAnnual : mainAnnuals){
                    if (mainAnnual.getId() != null &&
                            Optional.ofNullable(mainAnnual.getIsDeleted()).isPresent() && mainAnnual.getIsDeleted().intValue() == 1) {
                        mainAnnualService.removeById(mainAnnual.getId());
                    }else {
                        mainAnnual.setBaseBusinessAnnualId(baseBusinessAnnual.getId());
                        mainAnnualService.saveOrUpdate(mainAnnual);
                    }
                }
            }
            List<SelfAssessment> selfAssessments = baseBusinessAnnual.getSelfAssessments();
            if (CollectionUtil.isNotEmpty(selfAssessments)){
                for (SelfAssessment selfAssessment : selfAssessments){
                    if (selfAssessment.getId() != null &&
                            Optional.ofNullable(selfAssessment.getIsDeleted()).isPresent() && selfAssessment.getIsDeleted().intValue() == 1) {
                        selfAssessmentService.removeById(selfAssessment.getId());
                    }else {
                        selfAssessment.setBaseBusinessAnnualId(baseBusinessAnnual.getId());
                        selfAssessmentService.saveOrUpdate(selfAssessment);
                    }
                }
            }

        }
        return result;
    }

    @Override
    public R<BaseBusinessAnnualVO> getDetailObj(BaseBusinessAnnualVO baseBusinessAnnualVO) {
        if(!Optional.ofNullable(baseBusinessAnnualVO).isPresent()){
            return new R(CommonCode.FAIL);
        }
        List<BusinessAnnualVO> businessAnnualVOS = businessAnnualWrapper
                .entityToVO(businessAnnualService.list(new LambdaQueryWrapper<BusinessAnnual>()
                        .eq(BusinessAnnual::getBaseBusinessAnnualId, baseBusinessAnnualVO.getId())));

        if (CollectionUtil.isNotEmpty(businessAnnualVOS)){
            businessAnnualService.setDetailList(businessAnnualVOS);
        }
        baseBusinessAnnualVO.setBusinessAnnualVOS(businessAnnualVOS);

        // 查询指标分类
        List<AppraisalIndex> appIndexList = appraisalIndexService.list(new LambdaQueryWrapper<AppraisalIndex>()
                .eq(AppraisalIndex::getTableCode, "001").eq(AppraisalIndex::getType,1));
        Map<Long, List<BusinessAnnualVO>> map = businessAnnualVOS.stream().collect(Collectors.groupingBy(BusinessAnnualVO::getIndicatorsCategoryId, Collectors.toList()));
        if(CollectionUtil.isNotEmpty(appIndexList)){
            appIndexList.forEach(a ->{
                if(map.containsKey(a.getId()) && StringUtils.isNotBlank(a.getName())){
                    List<BusinessAnnualVO> list = map.get(a.getId());
//					list.forEach(b -> b.setIndicatorsCategoryName(a.getName()));
                    if("基本指标".equals(a.getName())){
                        baseBusinessAnnualVO.setBaseIndicatorsVOS(list);
                    } else if ("分类指标".equals(a.getName())) {
                        baseBusinessAnnualVO.setCategoryIndicatorsVOS(list);
                    } else if("行业指标".equals(a.getName())) {
                        baseBusinessAnnualVO.setIndustryIndicatorsVOS(list);
                    } else if("其他".equals(a.getName())) {
                        baseBusinessAnnualVO.setOtherIndicatorsVOS(list);
                    }
                }
            });
        }

        //任务绩效
        BaseBusinessProgressVO baseBusinessProgressVO = glcBaseBusinessProgressService.getBasicTaskProgress(baseBusinessAnnualVO.getFillingYear(), baseBusinessAnnualVO.getFillingUnitId());

        List<TaskAnnualVO> taskAnnualVOS = taskAnnualWrapper
                .entityToVO(taskAnnualService.list(new LambdaQueryWrapper<TaskAnnual>()
                        .eq(TaskAnnual::getBaseBusinessAnnualId, baseBusinessAnnualVO.getId())));
        setTaskProgress(taskAnnualVOS,baseBusinessProgressVO.getTaskProgressVOS());
        baseBusinessAnnualVO.setTaskAnnualVOS(taskAnnualVOS);


        //重大工程
        baseBusinessAnnualVO.setMajorProgressVOS(baseBusinessProgressVO.getMajorProgressVOS());

        //主责主业
        List<MainAnnualVO> mainAnnualVOS = mainAnnualWrapper
                .entityToVO(mainAnnualService.list(new LambdaQueryWrapper<MainAnnual>().eq(MainAnnual::getBaseBusinessAnnualId, baseBusinessAnnualVO.getId())));
        if (CollectionUtil.isNotEmpty(mainAnnualVOS)){
            mainAnnualService.setDetailList(mainAnnualVOS);
        }
        baseBusinessAnnualVO.setMainAnnualVOS(mainAnnualVOS);

        //企业自评
        List<SelfAssessment> selfAssessments = selfAssessmentService.list(new LambdaQueryWrapper<SelfAssessment>().eq(SelfAssessment::getBaseBusinessAnnualId, baseBusinessAnnualVO.getId()));
        baseBusinessAnnualVO.setSelfAssessments(selfAssessments);
        //履职成效
        baseBusinessAnnualVO.setEffectiveRate(baseBusinessProgressVO.getEffectiveRate());
        BaseBusinessIndicators indicators = glcBaseBusinessIndicatorsService.getById(baseBusinessAnnualVO.getBaseBusinessIndicatorsId());
        baseBusinessAnnualVO.setTargetValue(indicators.getTargetValue());
        baseBusinessAnnualVO.setRemarks(indicators.getRemarks());
        baseBusinessAnnualVO.setIsMajorProject(indicators.getIsMajorProject());

        R<BaseBusinessAnnualVO> objResult = new R<>(CommonCode.SUCCESS);
        objResult.setPageData(baseBusinessAnnualVO);
        return objResult;
    }

    @Override
    public BaseBusinessAnnualVO getDetailByBase(String fillingYear,String fillingUnitId){
        List<BaseBusinessAnnual> list = list(new LambdaQueryWrapper<BaseBusinessAnnual>().eq(BaseBusinessAnnual::getFillingYear, fillingYear)
                .eq(BaseBusinessAnnual::getModuleType,1).eq(BaseBusinessAnnual::getFillingUnitId, fillingUnitId));
        if (CollectionUtil.isNotEmpty(list)){
            BaseBusinessAnnual baseBusinessAnnual = list.get(0);
            BaseBusinessAnnualVO annualVO = getDetailObj(baseBusinessAnnualWrapper.entityToVO(baseBusinessAnnual)).getPageData();
            return annualVO;
        }else {
            return null;
        }
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 根据年度和企业获取基础表
     * @Date: 10:56 AM 2022/12/16
     * @Param: [dto]
     * @return: com.plian.system.vo.pf.BaseBusinessProgressVO
     **/
    @Override
    public BaseBusinessAnnualVO getDetailByDto(BaseBusinessAnnualDTO dto){
        BaseBusinessAnnualVO baseBusinessAnnualVO = new BaseBusinessAnnualVO();
        BaseBusinessIndicatorsVO indicatorsVO = glcBaseBusinessIndicatorsService.getDetailByDto(dto.getFillingYear(),dto.getFillingUnitId());
        //获取上个月  任务绩效
        BaseBusinessProgressVO businessProgressVO = glcBaseBusinessProgressService.getBasicTaskProgress(dto.getFillingYear(), dto.getFillingUnitId());
        List<TaskAnnualVO> taskAnnualVOS = new ArrayList<>();
        setTaskProgress(taskAnnualVOS,businessProgressVO.getTaskProgressVOS());
        baseBusinessAnnualVO.setTaskAnnualVOS(taskAnnualVOS);
        //重大工程
        baseBusinessAnnualVO.setMajorProgressVOS(businessProgressVO.getMajorProgressVOS());
        if (Optional.ofNullable(indicatorsVO).isPresent()){
            //主表Id
            baseBusinessAnnualVO.setBaseBusinessIndicatorsId(indicatorsVO.getId());
            //财务绩效
            setBusinessProgress(baseBusinessAnnualVO,businessProgressVO.getBusinessProgressVOS());
            //主责主业
            setMainProgress(baseBusinessAnnualVO,businessProgressVO.getMainProgressVOS());

            //履职成效
            baseBusinessAnnualVO.setEffectiveRate(businessProgressVO.getEffectiveRate());
            baseBusinessAnnualVO.setTargetValue(indicatorsVO.getTargetValue());
            baseBusinessAnnualVO.setRemarks(indicatorsVO.getRemarks());
            baseBusinessAnnualVO.setIsMajorProject(indicatorsVO.getIsMajorProject());
            baseBusinessAnnualVO.setStaffId(indicatorsVO.getStaffId());
            baseBusinessAnnualVO.setStaffName(indicatorsVO.getStaffName());
        }

        if (CollectionUtil.isNotEmpty(baseBusinessAnnualVO.getBusinessAnnualVOS())) {
            // 查询指标分类
            List<AppraisalIndex> appIndexList = appraisalIndexService.list(new LambdaQueryWrapper<AppraisalIndex>()
                    .eq(AppraisalIndex::getTableCode, "001").eq(AppraisalIndex::getType,1));
            Map<Long, List<BusinessAnnualVO>> map = baseBusinessAnnualVO.getBusinessAnnualVOS().stream().collect(Collectors.groupingBy(BusinessAnnualVO::getIndicatorsCategoryId, Collectors.toList()));
            if(CollectionUtil.isNotEmpty(appIndexList)){
                appIndexList.forEach(a ->{
                    if(map.containsKey(a.getId()) && StringUtils.isNotBlank(a.getName())){
                        List<BusinessAnnualVO> list = map.get(a.getId());
                        //					list.forEach(b -> b.setIndicatorsCategoryName(a.getName()));
                        if("基本指标".equals(a.getName())){
                            baseBusinessAnnualVO.setBaseIndicatorsVOS(list);
                        } else if ("分类指标".equals(a.getName())) {
                            baseBusinessAnnualVO.setCategoryIndicatorsVOS(list);
                        } else if("行业指标".equals(a.getName())) {
                            baseBusinessAnnualVO.setIndustryIndicatorsVOS(list);
                        } else if("其他".equals(a.getName())) {
                            baseBusinessAnnualVO.setOtherIndicatorsVOS(list);
                        }
                    }
                });
            }
        }

        return baseBusinessAnnualVO;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 放财务绩效
     * @Date: 10:49 AM 2022/12/16
     * @Param: [progressVO, businessIndicatorsVOS]
     * @return: void
     **/
    private void setBusinessProgress(BaseBusinessAnnualVO baseBusinessAnnualVO,List<BusinessProgressVO> businessProgressVOS){
        if (CollectionUtil.isNotEmpty(businessProgressVOS)){
            //VO 表/展示
            List<BusinessAnnualVO> businessAnnualVOS = new ArrayList<>();
            for (BusinessProgressVO vo :businessProgressVOS){
                //vo
                BusinessAnnualVO businessAnnualVO = new BusinessAnnualVO();
                businessAnnualVO.setBusinessIndicatorsId(vo.getBusinessIndicatorsId());
                businessAnnualVO.setIndicatorsCategoryName(vo.getIndicatorsCategoryName());
                businessAnnualVO.setIndicatorsWeight(vo.getIndicatorsWeight());
                businessAnnualVO.setBaseline(vo.getBaseline());
                businessAnnualVO.setTarget(vo.getTarget());
                businessAnnualVO.setBasicTarget(vo.getBasicTarget());
                businessAnnualVO.setIndicatorsCategoryId(vo.getIndicatorsCategoryId());
                if (Optional.ofNullable(vo.getPerformFill()).isPresent()){
                    businessAnnualVO.setAnnualSubmit(vo.getPerformFill());
                }else {
                    businessAnnualVO.setAnnualSubmit(vo.getPerformCalculate());
                }
                businessAnnualVOS.add(businessAnnualVO);
            }
            baseBusinessAnnualVO.setBusinessAnnualVOS(businessAnnualVOS);
        }
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 放任务绩效
     * @Date: 3:03 PM 2023/1/5
     * @Param: [taskAnnualVOS, taskProgressVOS]
     * @return: void
     **/
    private void setTaskProgress(List<TaskAnnualVO> taskAnnualVOS,List<TaskProgressVO> taskProgressVOS){
        if (CollectionUtil.isNotEmpty(taskProgressVOS)){
            if (CollectionUtil.isNotEmpty(taskAnnualVOS)){
                for (TaskAnnualVO taskAnnualVO :taskAnnualVOS){
                    List<TaskProgressVO> taskProgressVOList = taskProgressVOS.stream().filter(index -> taskAnnualVO.getTaskIndicatorsId().equals(index.getTaskIndicatorsId())).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(taskProgressVOList)){
                        TaskProgressVO vo = taskProgressVOList.get(0);
                        taskAnnualVO.setTaskIndicatorsId(vo.getTaskIndicatorsId());
                        taskAnnualVO.setIndicatorsCategoryName(vo.getIndicatorsCategoryName());
                        taskAnnualVO.setIndicatorsCategoryId(vo.getIndicatorsCategoryId());
                        taskAnnualVO.setIndexNum(vo.getIndexNum());
                        taskAnnualVO.setContent(vo.getContent());
                    }
                }
            }else {
                for (TaskProgressVO vo :taskProgressVOS){
                    //vo
                    TaskAnnualVO taskAnnualVO = new TaskAnnualVO();
                    taskAnnualVO.setTaskIndicatorsId(vo.getTaskIndicatorsId());
                    taskAnnualVO.setIndicatorsCategoryName(vo.getIndicatorsCategoryName());
                    taskAnnualVO.setIndicatorsCategoryId(vo.getIndicatorsCategoryId());
                    taskAnnualVO.setIndexNum(vo.getIndexNum());
                    taskAnnualVO.setContent(vo.getContent());
                    taskAnnualVO.setExecution(vo.getExecution());

                    taskAnnualVOS.add(taskAnnualVO);
                }
            }
        }else {
            //指标
            List<AppraisalIndex> indexList = appraisalIndexService.listByTableCode("001");
            List<TaskIndicators> taskIndicators = taskIndicatorsMapper.selectList(Wrappers.lambdaQuery());
            for (TaskAnnualVO taskAnnualVO :taskAnnualVOS){
                taskIndicators.stream().filter(indicator -> taskAnnualVO.getTaskIndicatorsId().equals(indicator.getId())).findFirst().ifPresent(vo ->{
                    taskAnnualVO.setIndexNum(vo.getIndexNum());
                    taskAnnualVO.setContent(vo.getContent());
                    indexList.stream().filter(m -> vo.getIndicatorsCategoryId().equals(m.getId())).findFirst().ifPresent(task ->{
                        taskAnnualVO.setIndicatorsCategoryName(task.getName());
                        taskAnnualVO.setIndicatorsCategoryId(task.getId());
                    });
                });
            }
        }
    }


    /**
     * @Author: Take-off
     * @Description: //TODO 放主责主业
     * @Date: 10:49 AM 2022/12/16
     * @Param: [progressVO, businessIndicatorsVOS]
     * @return: void
     **/
    private void setMainProgress(BaseBusinessAnnualVO baseBusinessAnnualVO,List<MainProgressVO> mainProgressVOS){
        if (CollectionUtil.isNotEmpty(mainProgressVOS)){
            //VO 表/展示
            List<MainAnnualVO> mainAnnualVOS = new ArrayList<>();
            for (MainProgressVO vo :mainProgressVOS){
                //vo
                MainAnnualVO mainAnnualVO = new MainAnnualVO();
                mainAnnualVO.setMainBusinessId(vo.getMainBusinessId());
                mainAnnualVO.setIndexNum(vo.getIndexNum());
                mainAnnualVO.setEvaluation(vo.getEvaluation());
                mainAnnualVO.setExecution(vo.getExecution());
                mainAnnualVOS.add(mainAnnualVO);
            }
            baseBusinessAnnualVO.setMainAnnualVOS(mainAnnualVOS);
        }
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 自动生成国资审核
     * @Date: 3:56 PM 2023/1/5
     * @Param: [baseBusinessAnnualVO]
     * @return: void
     **/
    private void saveBaseBusinessAudit(BaseBusinessAnnualVO baseBusinessAnnualVO){
        BaseBusinessAudit baseBusinessAudit = setBaseBusinessAudit(baseBusinessAnnualVO);
        if (!Optional.ofNullable(baseBusinessAudit.getId()).isPresent()){
            baseBusinessAuditMapper.insert(baseBusinessAudit);
            Long id = baseBusinessAudit.getId();
            //指标值
            List<IndicatorsValue> indicatorsValues = indicatorsValueMapper.selectList(new LambdaQueryWrapper<IndicatorsValue>().eq(IndicatorsValue::getFyear, baseBusinessAnnualVO.getFillingYear()).eq(IndicatorsValue::getFmonth, "00")
                    .eq(IndicatorsValue::getOrgId, baseBusinessAnnualVO.getFillingUnitId()));


            List<BusinessAudit> businessAudits = setBusinessAudits(id, baseBusinessAnnualVO.getBusinessAnnualVOS(),indicatorsValues);
            businessAuditService.saveOrUpdateBatch(businessAudits);
            List<TaskAudit> taskAudits = setTaskAudit(id, baseBusinessAnnualVO.getTaskAnnualVOS());
            taskAuditService.saveOrUpdateBatch(taskAudits);
            List<MainAudit> mainAudits = setMainAudit(id, baseBusinessAnnualVO.getMainAnnualVOS());
            mainAuditService.saveOrUpdateBatch(mainAudits);
            List<AuditAssets> auditAssets = setAuditAssets(id, baseBusinessAnnualVO.getSelfAssessments());
            auditAssetsService.saveOrUpdateBatch(auditAssets);
        }

    }

    /**
     * @Author: Take-off
     * @Description: //TODO 生成国资审核
     * @Date: 3:44 PM 2023/1/5
     * @Param: [baseBusinessAnnualVO]
     * @return: com.plian.system.entity.pf.BaseBusinessAudit
     **/
    private BaseBusinessAudit setBaseBusinessAudit(BaseBusinessAnnualVO baseBusinessAnnualVO){
        BaseBusinessAudit baseBusinessAudit = new BaseBusinessAudit();
        List<BaseBusinessAudit> baseBusinessAudits = baseBusinessAuditMapper.selectList(new LambdaQueryWrapper<BaseBusinessAudit>().eq(BaseBusinessAudit::getFillingYear, baseBusinessAnnualVO.getFillingYear())
                .eq(BaseBusinessAudit::getFillingUnitId, baseBusinessAnnualVO.getFillingUnitId()).eq(BaseBusinessAudit::getModuleType,1));
        if (CollectionUtil.isNotEmpty(baseBusinessAudits)){
            baseBusinessAudit = baseBusinessAudits.get(0);
        }else {
            baseBusinessAudit.setDataSource(baseBusinessAnnualVO.getDataSource());
            baseBusinessAudit.setFillingYear(baseBusinessAnnualVO.getFillingYear());
            baseBusinessAudit.setFillingUnitId(baseBusinessAnnualVO.getFillingUnitId());
            baseBusinessAudit.setFormType(FormTypeConstant.GLC_BUSINESS_ANNUAL +"");
            baseBusinessAudit.setBaseBusinessIndicatorsId(baseBusinessAnnualVO.getBaseBusinessIndicatorsId());
            baseBusinessAudit.setBaseAnnalId(baseBusinessAnnualVO.getId());
            baseBusinessAudit.setIsDeleted(0);
            baseBusinessAudit.setStatus(0);
            baseBusinessAudit.setModuleType(1);
            if(baseBusinessAnnualVO!=null){
                if(baseBusinessAnnualVO.getStaffId()!=null){
                    baseBusinessAudit.setStaffId(baseBusinessAnnualVO.getStaffId());
                }
                if(StringUtil.isNotBlank(baseBusinessAnnualVO.getStaffName())){
                    baseBusinessAudit.setStaffName(baseBusinessAnnualVO.getStaffName());
                }
            }

        }

        return baseBusinessAudit;
    }

    private List<BusinessAudit> setBusinessAudits(Long baseId,List<BusinessAnnualVO> businessAnnualVOS,  List<IndicatorsValue> indicatorsValues){
        List<BusinessAudit> businessAuditVOS =new ArrayList<>();
        List<AppraisalIndex> appraisalIndices = appraisalIndexService.list(new LambdaQueryWrapper<AppraisalIndex>().eq(AppraisalIndex::getType, 1));

        businessAnnualVOS.forEach(vo -> {
            BusinessAudit businessAudit = new BusinessAudit();
            businessAudit.setBaseBusinessAuditId(baseId);
            businessAudit.setBusinessIndicatorsId(vo.getBusinessIndicatorsId());
            businessAudit.setIndicatorsCategoryId(vo.getIndicatorsCategoryId());
            businessAudit.setAnnualSubmit(vo.getAnnualSubmit());
            businessAudit.setIsDeleted(0);
            if (Optional.ofNullable(vo.getIndicatorsCategoryId()).isPresent()){
                //todo 审定认定
                AppraisalIndex appraisalIndex = appraisalIndices.stream().filter(m -> m.getId().equals(vo.getIndicatorsCategoryId())).collect(Collectors.toList()).get(0);
                if (Optional.ofNullable(appraisalIndex.getFlag()).isPresent() && appraisalIndex.getFlag() == 0){
                    String reviewCode = appraisalIndex.getReviewCode();
                    FinanceIndicators financeIndicators=indicatorsMapper.selectOne(new LambdaQueryWrapper<FinanceIndicators>().eq(FinanceIndicators::getCode, reviewCode));
                    if(financeIndicators!=null){//需要判断要不然空指针20250210
                        String indictId = financeIndicators.getId();
                        if (CollectionUtil.isNotEmpty(indicatorsValues)){
                            List<IndicatorsValue> values = indicatorsValues.stream().filter(value -> indictId.equals(value.getIndicatorsId())).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(values)){
                                Optional<IndicatorsValue> indicatorsValue = values.stream().filter(m -> "1".equals(m.getIsGroup())).findFirst();
                                if (indicatorsValue.isPresent()){
                                    BigDecimal fvalue = indicatorsValue.get().getFvalue();
                                    businessAudit.setAuditFirmly(fvalue);
                                }else {
                                    BigDecimal fvalue = values.get(0).getFvalue();
                                    businessAudit.setAuditFirmly(fvalue);
                                }
                            }
                        }
                    }

                }
            }
            businessAuditVOS.add(businessAudit);
        });
        return businessAuditVOS;
    }

    private List<TaskAudit> setTaskAudit(Long baseId,List<TaskAnnualVO> taskProgressVOS){
        List<TaskAudit> taskAudits =new ArrayList<>();
        taskProgressVOS.forEach(vo -> {
            //vo
            TaskAudit taskAuditVO = new TaskAudit();
            taskAuditVO.setBaseBusinessAuditId(baseId);
            taskAuditVO.setTaskIndicatorsId(vo.getTaskIndicatorsId());
            taskAuditVO.setIndicatorsCategoryId(vo.getIndicatorsCategoryId());
            taskAuditVO.setIndexNum(vo.getIndexNum());
            taskAuditVO.setContent(vo.getContent());
            taskAuditVO.setAnnualSummary(vo.getExecution());
            taskAuditVO.setSelfScoring(vo.getSelfScoring());
            taskAuditVO.setIsDeleted(0);
            taskAudits.add(taskAuditVO);
        });
        return taskAudits;
    }

    private List<MainAudit> setMainAudit(Long baseId,List<MainAnnualVO> mainAnnualVOS){
        List<MainAudit> mainAuditVOS =new ArrayList<>();
        mainAnnualVOS.forEach(vo -> {
            //vo
            MainAudit mainAuditVO = new MainAudit();
            mainAuditVO.setBaseBusinessAuditId(baseId);
            mainAuditVO.setMainBusinessId(vo.getMainBusinessId());
            mainAuditVO.setIsDeleted(0);
            mainAuditVOS.add(mainAuditVO);
        });
        return mainAuditVOS;
    }

    private List<AuditAssets> setAuditAssets(Long baseId,List<SelfAssessment> assessments){
        List<AuditAssets> auditAssets =new ArrayList<>();
        assessments.forEach(vo -> {
            //vo
            AuditAssets assets = new AuditAssets();
            assets.setBaseBusinessAuditId(baseId);
            assets.setBaseAssessId(vo.getId());
            assets.setExecution(vo.getExecution());
            assets.setSelfScore(vo.getSelfScore());
            assets.setType(vo.getType());
            assets.setIsDeleted(0);
            auditAssets.add(assets);
        });
        return auditAssets;
    }

    @Override
    public String saveBaseAnnual(String data) {
        YthResult ythResult = new YthResult();
        List<String> successIds = new ArrayList<>();
        List<String> failIds = new ArrayList<>();
        List<String> failReasons = new ArrayList<>();

        List<BaseBusinessAnnual> dataList = JSON.parseArray(data, BaseBusinessAnnual.class);
        if (CollectionUtil.isNotEmpty(dataList)) {
            Map<String, String> orgSourceMap = orgService.getSourceId();
            List<BaseBusinessIndicators> indicators = glcBaseBusinessIndicatorsService.getSourceData();
            //根据datasourceIds 查询出所有的数据
            List<BaseBusinessAnnual> list = list(new LambdaQueryWrapper<BaseBusinessAnnual>().in(BaseBusinessAnnual::getDataSourceId, dataList.stream().map(BaseBusinessAnnual::getDataSourceId).toArray()).eq(BaseBusinessAnnual::getStatus, UNREVIEWED));
            if (CollectionUtil.isNotEmpty(list)) {
                //删除子集
                List<Long> ids = list.stream().map(BaseBusinessAnnual::getId).collect(Collectors.toList());
                businessAnnualService.deleteByParentId(ids);
                taskAnnualService.deleteByParentId(ids);
                mainAnnualService.deleteByParentId(ids);
                selfAssessmentService.deleteByParentId(ids);
            }
            for (BaseBusinessAnnual entity:dataList){
                transfer(entity,orgSourceMap,indicators);
                //id重复略过
                if (CollectionUtil.isNotEmpty(list)){
                    List<String> olIds = list.stream().map(BaseBusinessAnnual::getDataSourceId).collect(Collectors.toList());
                    String dataSourceId = entity.getDataSourceId();
                    //判断数据库中是否有数据
                    if (olIds.contains(dataSourceId)){
                        for (BaseBusinessAnnual oldEntity:list){
                            if (dataSourceId.equals(oldEntity.getDataSourceId())){
                                //判断status是否为0，如果是0，就更新，不是0，就不更新
                                if (CheckStatus.checkCode(oldEntity.getStatus())){
                                    successIds.add(dataSourceId);
                                    entity.setId(oldEntity.getId());
                                    entity.setDataSource(YthConstant.DATA_NINGBO);
                                    submit(entity);
                                    list.remove(oldEntity);
                                    break;
                                }else {
                                    failIds.add(dataSourceId);
                                    failReasons.add("dataSourceId:"+dataSourceId+"数据已提交且已经在流程中，无法更新");
                                    break;
                                }
                            }
                        }
                    }else {
                        //如果数据库中没有数据，就新增
                        entity.setDataSource(YthConstant.DATA_NINGBO);
                        submit(entity);
                        successIds.add(entity.getDataSourceId());
                    }
                }else {
                    //如果数据库中没有数据，就新增
                    entity.setDataSource(YthConstant.DATA_NINGBO);
                    submit(entity);
                    successIds.add(entity.getDataSourceId());
                }
            }
        }else {
            failReasons.add("数据为空");
        }
        ythResult.setSuccessIds(successIds);
        ythResult.setFailIds(failIds);
        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
        //ythResult转换成json字符串
        return JSON.toJSONString(ythResult);
    }

    private void transfer(BaseBusinessAnnual entity, Map<String, String> orgSourceMap,List<BaseBusinessIndicators> indicators){
        Optional.ofNullable(entity.getFillingUnitId()).ifPresent(m ->
                {
                    String orgId = orgSourceMap.get(m);
                    if (StringUtil.isNotBlank(orgId)){
                        entity.setFillingUnitId(orgId);
                        entity.setCreateCompanyId(orgId);
                    }
                }
        );
        //转换code
        String baseIndicatorsCodeId = entity.getBaseIndicatorsCodeId();
        if (Optional.ofNullable(baseIndicatorsCodeId).isPresent()){
            Optional<BaseBusinessIndicators> indicatorsOptional = indicators.stream().filter(m -> baseIndicatorsCodeId.equals(m.getDataSourceId())).findFirst();
            if (indicatorsOptional.isPresent()){
                BaseBusinessIndicators baseIndicator = indicatorsOptional.get();
                entity.setBaseBusinessIndicatorsId(baseIndicator.getId());
                List<BusinessAnnual> businessAnnuals = entity.getBusinessAnnuals();
                if (CollectionUtil.isNotEmpty(businessAnnuals)){
                    List<BusinessIndicators> businessIndicators = baseIndicator.getBusinessIndicators();
                    businessAnnuals.forEach( bus ->{
                        Optional<BusinessIndicators> optional = businessIndicators.stream().filter(m -> bus.getIndicatorsCodeId().equals(m.getDataSourceId())).findFirst();
                        if (optional.isPresent()){
                            BusinessIndicators indicator= optional.get();
                            bus.setBusinessIndicatorsId(indicator.getId());
                            bus.setIndicatorsWeight(indicator.getIndicatorsWeight());
                            bus.setBaseline(indicator.getBaseline());
                            bus.setTarget(indicator.getTarget());
                            bus.setBasicTarget(indicator.getBasicTarget());
                        }
                    });
                }
                List<TaskAnnual> taskAnnuals = entity.getTaskAnnuals();
                if (CollectionUtil.isNotEmpty(taskAnnuals)){
                    List<TaskIndicators> taskIndicators = baseIndicator.getTaskIndicators();
                    taskAnnuals.forEach( task ->{
                        Optional<TaskIndicators> optional = taskIndicators.stream().filter(m -> task.getIndicatorsCodeId().equals(m.getDataSourceId())).findFirst();
                        if (optional.isPresent()){
                            TaskIndicators indicator= optional.get();
                            task.setTaskIndicatorsId(indicator.getId());
                        }
                    });
                }
                List<MainAnnual> mainAnnuals = entity.getMainAnnuals();
                if (CollectionUtil.isNotEmpty(mainAnnuals)){
                    List<MainBusiness> mainBusinesses = baseIndicator.getMainBusinesses();
                    mainAnnuals.forEach( major ->{
                        Optional<MainBusiness> optional = mainBusinesses.stream().filter(m -> major.getIndicatorsCodeId().equals(m.getDataSourceId())).findFirst();
                        if (optional.isPresent()){
                            MainBusiness mainBusiness = optional.get();
                            major.setMainBusinessId(mainBusiness.getId());
                        }
                    });
                }


            }
        }
    }

}
